package com.hod.client.frontend;

import java.util.Date;

import com.gwtext.client.core.SortDir;
import com.gwtext.client.core.TextAlign;
import com.gwtext.client.data.DataProxy;
import com.gwtext.client.data.DateFieldDef;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.JsonReader;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.ScriptTagProxy;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.util.DateUtil;
import com.gwtext.client.util.Format;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.PagingToolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.grid.CellMetadata;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GridView;
import com.gwtext.client.widgets.grid.Renderer;
import com.gwtext.client.widgets.grid.RowParams;
import com.gwtext.client.widgets.grid.RowSelectionModel;

public class ComplexDataGrid extends GridPanel{
    private boolean showPreview = true;
    private String pagingToolbarDisplayMsg = "{0} - {1} of {2}";
    private String pagingToolbarEmptyMsg = "No topics to display";
    private String showingPreview = "Preview";
    private int width = 700;
    private int height = 500;
    private String title = "Remote Paging Grid";
    
    private final RecordDef recordDef = new RecordDef(new FieldDef[]{
            new StringFieldDef("title"),
            new StringFieldDef("forumtitle"),
            new StringFieldDef("forumid"),
            new StringFieldDef("author"),
            new IntegerFieldDef("replycount"),
            new DateFieldDef("lastpost", "lastpost", "timestamp"),
            new StringFieldDef("lastposter"),
            new StringFieldDef("excerpt")
    });
    
    
    
    protected ColumnModel setcolumnModel(){
    	Renderer renderTopic = new Renderer() {
            public String render(Object value, CellMetadata cellMetadata, Record record, int rowIndex, int colNum, Store store) {
                return Format.format("<b><a href=\"http://extjs.com/forum/showthread.php?t={2}\" target=\"_blank\">{0}</a></b><a href=\"http://extjs.com/forum/forumdisplay.php?f={3}\" target=\"_blank\">{1} Forum</a>",
                        new String[]{(String) value,
                                record.getAsString("forumtitle"),
                                record.getId(),
                                record.getAsString("forumid"),
                        });
            }
        };

        Renderer renderLast = new Renderer() {
            public String render(Object value, CellMetadata cellMetadata, Record record, int rowIndex, int colNum, Store store) {
                Date lastPost = record.getAsDate("lastpost");
                String lastPostStr = DateUtil.format(lastPost, "M j, Y, g:i a");
                return Format.format("{0}<br/>by {1}", new String[]{lastPostStr, record.getAsString("lastposter")});
            }
         };
    	 ColumnConfig topicColumn = new ColumnConfig("Topic", "title", 420, false, renderTopic, "topic");
         topicColumn.setCss("white-space:normal;");

         ColumnConfig authorColumn = new ColumnConfig("Author", "author", 100);
         authorColumn.setHidden(true);

         ColumnConfig repliesColumn = new ColumnConfig("Replies", "replycount", 70);
         repliesColumn.setAlign(TextAlign.RIGHT);

         ColumnConfig lastPostColumn = new ColumnConfig("Last Post", "lastPost", 150, true, renderLast, "last");

         ColumnModel columnModel = new ColumnModel(new ColumnConfig[]{
                 topicColumn,
                 authorColumn,
                 repliesColumn,
                 lastPostColumn
         });
         columnModel.setDefaultSortable(true);
         return columnModel;
    }
    
    protected Store configureStore(){
    	DataProxy dataProxy = new ScriptTagProxy("http://extjs.com/forum/topics-browse-remote.php");		
        JsonReader reader = new JsonReader(recordDef);
        reader.setRoot("topics");
        reader.setTotalProperty("totalCount");
        reader.setId("threadid");

        final Store store = new Store(dataProxy, reader, true);
        store.setDefaultSort("forumid", SortDir.ASC);
        return store;
    }
    
    protected GridView setGridView(){
    	GridView view = new GridView() {
            public String getRowClass(Record record, int index, RowParams rowParams, Store store) {
                if (showPreview) {
                    rowParams.setBody(Format.format("<p>{0}</p>", record.getAsString("excerpt")));
                    return "x-grid3-row-expanded";
                } else {
                    return "x-grid3-row-collapsed";
                }
            }
        };
        view.setForceFit(true);
        view.setEnableRowBody(true);
        return view;
    }
    
    protected void setPagingToolbar(){
    	PagingToolbar pagingToolbar = new PagingToolbar(getStore());
        pagingToolbar.setPageSize(25);
        pagingToolbar.setDisplayInfo(true);
        pagingToolbar.setDisplayMsg(pagingToolbarDisplayMsg);
        pagingToolbar.setEmptyMsg(pagingToolbarEmptyMsg);

        pagingToolbar.addSeparator();
        ToolbarButton toolbarButton = new ToolbarButton(showingPreview);
        toolbarButton.setPressed(showPreview);
        toolbarButton.setEnableToggle(true);
        toolbarButton.setCls("x-btn-text-icon details");
        toolbarButton.addListener(new ButtonListenerAdapter() {
            public void onToggle(Button button, boolean pressed) {
                toggleDetails(pressed);
            }
        });

        pagingToolbar.addButton(toolbarButton);
        setBottomToolbar(pagingToolbar);

        addListener(new PanelListenerAdapter() {
            public void onRender(Component component) {
                getStore().load(0, 25);
            }
        });
    }

    
	public ComplexDataGrid() {
		   //super();
		 setWidth(width);
	        setHeight(height);
	        setTitle(title);
	        setStore(configureStore());
	        setColumnModel(setcolumnModel());
	        setTrackMouseOver(false);
	        setLoadMask(true);
	        setSelectionModel(new RowSelectionModel());
	        setFrame(true);
	        setStripeRows(true);
	        setIconCls("grid-icon");        
	        setView(setGridView());
	        setPagingToolbar();
        
	}
	
    private void toggleDetails(boolean pressed) {
        showPreview = pressed;
        getView().refresh();
    }


}
